﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMS.BLL;
using PMS.Entity;
using PMS.Resources;
using PMS.Win;
using PMS.Utils;
using DevExpress.XtraEditors.Mask;
using PMS.DanhMucChung;
using System.Collections.Generic;
using PMS.ValidationRules;
using System.Collections;

namespace PMS.SYS
{
    public partial class AccountEntry : FormEntryBase
    {
        #region Constants
        private const string BINDING_PROPERTY = "EditValue";
        #endregion

        #region Private Members
        protected AccountBO m_Service;
        private List<ComboItem> m_RoleList;
        #endregion

        #region Properties
        protected Entity.Account CurrentAccountEntry
        {
            get
            {
                return base.Entity as Entity.Account;
            }
            set
            {
                base.Entity = value;
            }
        }
        #endregion

        #region Services
        public AccountBO Service
        {
            get
            {
                if (m_Service == null)
                {
                    m_Service = new AccountBO();
                }
                return m_Service;
            }
        }
        #endregion

        #region Constructors
        public AccountEntry(string functionID)
            : base(functionID)
        {
            InitializeComponent();
            Init();
        }
        #endregion

        #region Init Data and Style
        private void Init()
        {
            InitData();
            InitStyle();
        }

        private void InitData()
        {
            LoadRoleCbbData();
        }

        private void InitStyle()
        {
            bteUsername.BackColor = REQUIRED_FIELD_COLOR;
            txtPassword.BackColor = REQUIRED_FIELD_COLOR;
            txtRePass.BackColor = REQUIRED_FIELD_COLOR;
            cbbRole.BackColor = REQUIRED_FIELD_COLOR;
            txtFullName.BackColor = REQUIRED_FIELD_COLOR;

            this.bteUsername.Properties.MaxLength = 12;
            this.txtFullName.Properties.MaxLength = 35;
            this.txtAddress.Properties.MaxLength = 30;
            this.txtPhone.Properties.MaxLength = 15;
            this.txtEmail.Properties.MaxLength = 25;
            this.txtPosition.Properties.MaxLength = 50;
            this.txtMoreInfo.Properties.MaxLength = 200;

            cbbRole.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
        }
        #endregion

        #region override methods

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (this.CurrentAccountEntry == null)
            {
                this.DoNew();
            }
        }

        protected override void BindingToControls(IBaseEntity entity)
        {
            base.BindingToControls(entity);

            this.bteUsername.DataBindings.Clear();
            this.txtFullName.DataBindings.Clear();
            this.txtAddress.DataBindings.Clear();
            this.txtPhone.DataBindings.Clear();
            this.txtEmail.DataBindings.Clear();
            this.txtPosition.DataBindings.Clear();
            this.txtMoreInfo.DataBindings.Clear();

            this.bteUsername.DataBindings.Add(BINDING_PROPERTY, entity, AccountColumns.ID.ToString());
            this.txtFullName.DataBindings.Add(BINDING_PROPERTY, entity, AccountColumns.Hoten.ToString());
            this.txtAddress.DataBindings.Add(BINDING_PROPERTY, entity, AccountColumns.Diachi.ToString());
            this.txtPhone.DataBindings.Add(BINDING_PROPERTY, entity, AccountColumns.SoDT.ToString());
            this.txtEmail.DataBindings.Add(BINDING_PROPERTY, entity, AccountColumns.Email.ToString());
            this.txtPosition.DataBindings.Add(BINDING_PROPERTY, entity, AccountColumns.Chucvu.ToString());
            this.txtMoreInfo.DataBindings.Add(BINDING_PROPERTY, entity, AccountColumns.Thongtinkhac.ToString());

            Account ac = entity as Account;
            SetRoleCbb(ac.Role);

            if (!string.IsNullOrEmpty(ac.ID))
            {
                txtPassword.Properties.ReadOnly = true;
                txtRePass.Properties.ReadOnly = true;

                txtPassword.BackColor = DISABLE_FIELD_COLOR;
                txtRePass.BackColor = DISABLE_FIELD_COLOR;
                
            }
            else
            {
                txtPassword.Properties.ReadOnly = false;
                txtRePass.Properties.ReadOnly = false;
                txtPassword.BackColor = REQUIRED_FIELD_COLOR;
                txtRePass.BackColor = REQUIRED_FIELD_COLOR;
            }

        }

        protected override void FocusFirtsControl()
        {
            base.FocusFirtsControl();
            this.bteUsername.Focus();
        }

        protected override void InitValidationRules()
        {
            base.InitValidationRules();
            Validator validate = new Validator(ValidationProvider);
            validate.AddValidationRule(base.CreateNotEmptyValidationRule());
            SetValidator(validate, bteUsername);
            SetValidator(validate, txtPassword);
            SetValidator(validate, cbbRole);
            SetValidator(validate, txtFullName);

        }

        public override void New()
        {
            this.CurrentAccountEntry = new Entity.Account
                {
                    Role = (int)AccountRole.User
                };
            txtRePass.EditValue = string.Empty;
            txtPassword.EditValue = string.Empty;
            base.New();
        }

        protected override bool Save()
        {
            try
            {
                if (IsNew)
                {
                    CurrentAccountEntry.Matkhau = DataConvertUltils.ToString(txtRePass.EditValue);
                    CurrentAccountEntry = Service.CreateAccount(CurrentAccountEntry);
                }
                else
                {
                    Service.UpdateAccount(CurrentAccountEntry);
                }
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        protected override bool Delete()
        {
            try
            {
                Service.DeleteAccount(CurrentAccountEntry);
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        public override void Cancel()
        {
            //your code here
            base.Cancel();
        }

        protected override IBaseEntity GetEntity()
        {
            //need to get the latest record of the current Entity's ID or code then return it
            return base.GetEntity();
        }

        protected override void ClearData()
        {
            New();
        }
        #endregion

        #region Lookups
        #endregion

        #region Form's function

        private void LoadRoleCbbData()
        {
            ArrayList tempItemList = BindDataUtil.BindDataCombobox("AccountRole", typeof(AccountRole));
            m_RoleList = new List<ComboItem>();
            foreach (ComboItem item in tempItemList)
            {
                m_RoleList.Add(item);
            }
            cbbRole.Properties.Items.AddRange(m_RoleList);
        }

        private void SetRoleCbb(int role)
        {
            switch (role)
            {
                case (byte)AccountRole.Admin:
                    this.cbbRole.SelectedItem = m_RoleList.Find(item => item.ItemValue == (int)AccountRole.Admin);
                    break;
                case (byte)AccountRole.User:
                    this.cbbRole.SelectedItem = m_RoleList.Find(item => item.ItemValue == (int)AccountRole.User);
                    break;
            }
        }

        private void LoadObjectOnForm(string previousCode, string code, IBaseEntity ObjectLoad)
        {
            if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
            {
                if (IsNew)
                {
                    if (ObjectLoad != null)
                    {
                        if (IsDataChanged)
                        {
                            var result = ShowSaveConfimMessage();
                            if (result == DialogResult.Yes)
                            {
                                CurrentAccountEntry.ID = previousCode;
                                if (!base.ValidateControls() || !Save())
                                {
                                    return;
                                }
                            }
                        }
                        Entity = ObjectLoad;
                        IsNew = false;
                        IsDataChanged = false;
                    }
                    else
                    {
                        CurrentAccountEntry.ID = code;
                        Entity = CurrentAccountEntry;
                        IsNew = true;//important
                        IsDataChanged = true;//important                        
                    }
                }
                else
                {
                    if (!IsDataChanged)
                    {
                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentAccountEntry = new Account();
                            CurrentAccountEntry.ID = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentAccountEntry;
                            IsNew = true;//important
                            IsDataChanged = true;//important   
                        }
                    }
                    else
                    {
                        var result = ShowSaveConfimMessage();
                        if (result == DialogResult.Yes)
                        {
                            CurrentAccountEntry.ID = previousCode;
                            if (!base.ValidateControls() || !Save())
                            {
                                return;
                            }
                        }

                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentAccountEntry = new Account();
                            CurrentAccountEntry.ID = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentAccountEntry; ;
                            IsNew = true;//important
                            IsDataChanged = true;//important 
                        }
                    }
                }
                ClearErrorMessage();
            }
        }
        #endregion

        private void bteUsername_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                string username = DataConvertUltils.ToString(CurrentAccountEntry.ID);
                AccountLookup form = new AccountLookup();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.AccountSelected != null)
                    {
                        LoadObjectOnForm(username, form.AccountSelected.ID, form.AccountSelected);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteUsername_Leave(object sender, EventArgs e)
        {
            try
            {
                string id = DataConvertUltils.ToString(bteUsername.EditValue);
                if (!string.IsNullOrEmpty(id))
                {
                    Account ac = Service.GetAccountByID(id);
                    if (ac != null)
                    {
                        LoadObjectOnForm(CurrentAccountEntry.ID, id, ac);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void cbbRole_SelectedValueChanged(object sender, EventArgs e)
        {
            CurrentAccountEntry.Role = (int)((ComboItem)cbbRole.SelectedItem).ItemValue;
        }

        private void txtPassword_Leave(object sender, EventArgs e)
        {
            string pass = DataConvertUltils.ToString(txtPassword.EditValue);
           Validator validate = new Validator(ValidationProvider);
           validate.AddValidationRule(new PasswordValidateRule(pass,true));
           SetValidator(validate, txtRePass);
        }
    }
}
